package org.zebra.tenant.redis;

import cn.hutool.core.util.StrUtil;
import org.redisson.api.NameMapper;
import org.zebra.tenant.TenantHelper;

import java.io.Serializable;

/**
 * redisson 多租户key
 *
 * @author zhanghongbin
 */
public class TenantNameMapper implements NameMapper {

    @Override
    public String map(String name) {
        if (StrUtil.isBlank(name)) {
            return null;
        }
        Serializable tenantId = TenantHelper.getTenantId();
        if (tenantId != null) {
            return tenantId + ":" + name;
        }
        return name;
    }

    @Override
    public String unmap(String name) {
        if (StrUtil.isBlank(name)) {
            return null;
        }
        Serializable tenantId = TenantHelper.getTenantId();
        if (tenantId != null) {
            return name.substring(tenantId.toString().length() + 1);
        }
        return name;
    }
}
